Euler Problem 10

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.


In [2]:
N = 2000000
prime = [True] * N
prime_sum = 0
for p in range(2, N):
    if prime[p]:
        prime_sum += p
        for m in range(p*p, N, p):
            prime[m] = False
print(prime_sum)


142913828922

Explanation: We use the sieve of Eratosthenes to find all primes less than two million. If $p$ is prime, then we add $p$ to prime_sum, and we mark all multiples of $p$ as composite, starting with $p^2$. The reason that we can start with $p^2$ is that all smaller multiples of $p$ will have been marked already.

We could speed up this program by iterating through the odd numbers.

Alternative solution:


In [3]:
from primesieve import primes
print(sum(primes(N)))


142913828922

In [ ]: